package com.cheung.leetcode.stackandqueue;

import org.junit.jupiter.api.Test;

import java.util.*;

/**
 * @BelongsProject : java-leetcode
 * @BelongsPackage : com.cheung.leetcode.stackandqueue
 * @Author :  cheungming
 * @CreateTime : 2024-05-14 09:28:24
 * @Description : 堆
 * @Version : 1.0
 */
public class Code347Test {

    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }

        // 创建一个优先队列，比较次数，优先队列存储的是(key,value)
        PriorityQueue<int[]> queue = new PriorityQueue<>((o1, o2) -> o2[1] - o1[1]);

        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            queue.add(new int[]{entry.getKey(), entry.getValue()});
        }

        int[] result = new int[k];
        for (int i = 0; i < k; i++) {
            result[i] = Objects.requireNonNull(queue.poll())[0];
        }

        return result;

    }


    @Test
    public void test1() {
        int[] nums = {1, 1, 1, 2, 2, 3};
        int k = 2;
        int[] result = topKFrequent(nums, k);
        assert Arrays.equals(new int[]{1, 2}, result);
    }

    @Test
    public void test2() {
        int[] nums = {1};
        int k = 1;
        assert Arrays.equals(new int[]{1}, topKFrequent(nums, k));
    }
}
